//
//  YLGoodsDetailViewController.m
//  YLFinanceService
//
//  Created by she1323 on 2017/9/6.
//  Copyright © 2017年 she1323. All rights reserved.
//

#import "YLGoodsDetailViewController.h"
#import "YLGlobeHeader.h"
#import <Masonry.h>
#import "UIView+Extension.h"
#import "YLGoodsDetailHeaderView.h"
#import "YLMallGoodDetailTitleCell.h"
#import "YLMallGoodsTitleHeader.h"
#import <WebKit/WebKit.h>
#import "YLWebViewTableViewCell.h"
#import "YLMallGoodExchangeBottomTab.h"
#import "YLMallGoodsExchangeBuyView.h"
#import "YLOrderViewController.h"
#import "YLMallGoodDetailViewModel.h"
#import "YLMallGoodModel.h"
#import "WHProgressHUD.h"
#import "YLMyInfoModel.h"
@interface YLGoodsDetailViewController ()<UITableViewDelegate, UITableViewDataSource,WKNavigationDelegate>
@property (nonatomic, weak) UITableView *tableView;
@property (nonatomic, assign) CGFloat webHeight;
@property (nonatomic, strong) WKWebView *webView;
@property (nonatomic, assign) NSInteger cellRefreshCount;
@property (nonatomic, strong) UIScrollView *scrollView;

@property (nonatomic, strong) YLMallGoodDetailViewModel *viewModel;

@property (nonatomic, weak) YLGoodsDetailHeaderView *headerView;

@property (nonatomic, weak) YLMallGoodExchangeBottomTab *bottomTab;

//@property (nonatomic, strong) YLMineViewModel *myInfoViewModel;
@end

@implementation YLGoodsDetailViewController

- (YLMallGoodDetailViewModel *)viewModel
{
    if (!_viewModel) {
        _viewModel = [[YLMallGoodDetailViewModel alloc] init];
    }
    return _viewModel;
}

//- (YLMineViewModel *)myInfoViewModel
//{
//    if (!_myInfoViewModel) {
//        _myInfoViewModel = [[YLMineViewModel alloc] init];
//    }
//    return _myInfoViewModel;
//}
//

- (void)viewDidLoad {
    [super viewDidLoad];
    _cellRefreshCount = 0;
    _scrollView = [[UIScrollView alloc] init];
    
    
    // 注册加载完成高度的通知
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(noti:) name:@"WEBVIEW_HEIGHT" object:nil];
    _webHeight = 0;
    [self setUp];
    
    
    UITableView *tableView = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStyleGrouped];
    tableView.backgroundColor = [UIColor whiteColor];
    _tableView = tableView;
    [self.view addSubview:tableView];
    __weak typeof(self) weakSelf = self;
    [tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.right.left.mas_equalTo(weakSelf.view);
        make.bottom.mas_equalTo(weakSelf.view).mas_offset(-64);
    }];
    
    tableView.delegate = self;
    tableView.dataSource = self;
    
    [self initBottom];
    
    [tableView registerNib:[UINib nibWithNibName:NSStringFromClass([YLMallGoodDetailTitleCell class]) bundle:nil] forCellReuseIdentifier:[YLMallGoodDetailTitleCell cellID]];
    
    YLGoodsDetailHeaderView *header = [[YLGoodsDetailHeaderView alloc] initWithFrame:CGRectMake(0, 0, YLScreenW, YLScreenW * 418 / 496.0)];
    tableView.tableHeaderView = header;
    _headerView = header;
    
    [self initWebView];
    
    [self setUpData];

    [[self.viewModel.requestCommand execute:_pointProductId] subscribeNext:^(id  _Nullable x) {
        weakSelf.model = weakSelf.viewModel.model;
        [weakSelf.webView loadHTMLString:weakSelf.model.detail baseURL:nil];
        [weakSelf setUpData];
    }];
}


- (void)setUpData
{
    if (_model.pointProductImage.count > 0) {
        YLMallGoodBigIcon *icon = _model.pointProductImage.firstObject;
        _headerView.imageUrl = icon.imageUrl;
    } else {
        _headerView.imageUrl = _model.pointProductIcon;
    }
    _bottomTab.neetPoint = _model.neetPoint;
    [self.tableView reloadData];
}
- (void)initWebView
{
    WKWebViewConfiguration *wkWebConfig = [[WKWebViewConfiguration alloc] init];
    WKUserContentController *wkUController = [[WKUserContentController alloc] init];
    wkWebConfig.userContentController = wkUController;
    // 自适应屏幕宽度js
    NSString *jSString = @"var meta = document.createElement('meta'); meta.setAttribute('name', 'viewport'); meta.setAttribute('content', 'width=device-width'); document.getElementsByTagName('head')[0].appendChild(meta);";
    WKUserScript *wkUserScript = [[WKUserScript alloc] initWithSource:jSString injectionTime:WKUserScriptInjectionTimeAtDocumentEnd forMainFrameOnly:YES];
    // 添加js调用
    [wkUController addUserScript:wkUserScript];
    
    self.webView = [[WKWebView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, 1) configuration:wkWebConfig];
    self.webView.backgroundColor = [UIColor clearColor];
    self.webView.opaque = NO;
    self.webView.userInteractionEnabled = NO;
    self.webView.scrollView.bounces = NO;
    [self.webView sizeToFit];
    [self.tableView registerClass:[UITableViewCell class] forCellReuseIdentifier:@"WebViewCell"];
    [self.webView.scrollView addObserver:self forKeyPath:@"contentSize" options:NSKeyValueObservingOptionNew context:nil];
    //[self.webView loadHTMLString:self.model.detail baseURL:nil];
    
    self.scrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, 1)];
    [self.scrollView addSubview:self.webView];
    
    
}

// KVO具体实现
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSString *,id> *)change context:(void *)context
{
    if ([keyPath isEqualToString:@"contentSize"]) {
        
        UIScrollView *scrollView = (UIScrollView *)object;
        CGFloat height = scrollView.contentSize.height;
        _webHeight = height;
        _webView.frame = CGRectMake(0, 0, YLScreenW, height);
        _scrollView.frame = CGRectMake(0, 0, YLScreenW, height);
        _scrollView.contentSize =CGSizeMake(YLScreenW, height);
        [self.tableView reloadRowsAtIndexPaths:[NSArray arrayWithObjects:[NSIndexPath indexPathForRow:0 inSection:1], nil] withRowAnimation:UITableViewRowAnimationNone];
    }
}

// 别忘注销kvo
- (void)dealloc
{
    
    [_webView.scrollView removeObserver:self forKeyPath:@"contentSize"];
    _webView = nil;
    [_scrollView removeFromSuperview];
    
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    if (!_model) {
        return 0;
    }
    return 2;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return 1;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 0) {
        YLMallGoodDetailTitleCell *cell = [tableView dequeueReusableCellWithIdentifier:[YLMallGoodDetailTitleCell cellID]];
        cell.model = _model;
        return cell;
    }
    
    UITableViewCell *cell =
        cell = [tableView dequeueReusableCellWithIdentifier:@"WebViewCell"];
    
    [cell.contentView addSubview:_scrollView];
    
    return cell;
}

#pragma mark - 通知
- (void)noti:(NSNotification *)sender
{
   CGFloat height = [sender.userInfo[@"height"] floatValue];
    
    _cellRefreshCount ++;
    if (_webHeight != height) {
        _webHeight = height;
        [self.tableView reloadRowsAtIndexPaths:@[[NSIndexPath indexPathForRow:0 inSection:1]] withRowAnimation:UITableViewRowAnimationNone];
    }
    
    }


- (void)setUp
{
    self.title = @"产品详情";
    self.view.backgroundColor = [UIColor whiteColor];
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 1) {
        return _webHeight;
    }
    return 71.5;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    if (section == 1) {
        return 35;
    }
    
    return 0.001;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    if (section == 1) {
        YLMallGoodsTitleHeader *header = [[YLMallGoodsTitleHeader alloc] init];
        return header;
    }
    return nil;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    return 0.001;
}

- (void)initBottom
{
    __weak typeof(self) weakSelf = self;
  
    // 购买view
    YLMallGoodsExchangeBuyView *buyView = [[YLMallGoodsExchangeBuyView alloc] init];
    [self.view addSubview:buyView];

    [buyView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.mas_equalTo(weakSelf.view);
        make.top.mas_equalTo(weakSelf.view.mas_bottom);
        make.height.mas_equalTo(64);
    }];
    
    [buyView.closeSubject subscribeNext:^(id  _Nullable x) {
        [weakSelf.view layoutIfNeeded];
        buyView.show = NO;
        [buyView mas_remakeConstraints:^(MASConstraintMaker *make) {
            make.left.right.mas_equalTo(weakSelf.view);
            make.top.mas_equalTo(weakSelf.view.mas_bottom);
            make.height.mas_equalTo(88);
        }];
        [UIView animateWithDuration:0.5 animations:^{
            [weakSelf.view layoutIfNeeded];
        }];
    }];
    
    // 工具栏
    YLMallGoodExchangeBottomTab *tab = [[YLMallGoodExchangeBottomTab alloc] init];
    _bottomTab = tab;
    [self.view addSubview:tab];
    
    [tab mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.left.right.mas_equalTo(weakSelf.view);
        make.top.mas_equalTo(weakSelf.tableView.mas_bottom);
    }];
    
    
    [tab.exchangeSubject subscribeNext:^(id  _Nullable x) {
        if (buyView.show == YES) {
            
            
            if (weakSelf.model.amountIndex < [buyView.number integerValue]) {
                [weakSelf showWithTitle:@"抱歉，库存不足"];
                return ;
            }
            
            
            weakSelf.model.count = buyView.number;
            NSInteger totalPoint = ([weakSelf.model.neetPoint integerValue]) * ([weakSelf.model.count integerValue]);
            weakSelf.model.totalNeetPoint = [NSString stringWithFormat:@"%zd", totalPoint];
        
            if (totalPoint > weakSelf.pointQuota) {
            
                [weakSelf showWithTitle:@"您的可用积分不足"];
                return ;
            }
            
            YLOrderViewController *order = [[YLOrderViewController alloc] init];
            
            order.model = weakSelf.model;
            [weakSelf.navigationController pushViewController:order animated:YES];
           
        } else {
            buyView.show = YES;
            [weakSelf.view layoutIfNeeded];
            [buyView mas_remakeConstraints:^(MASConstraintMaker *make) {
                make.left.right.mas_equalTo(weakSelf.view);
                make.bottom.mas_equalTo(tab.mas_top);
                make.height.mas_equalTo(88);
            }];
            
            [UIView animateWithDuration:0.5 animations:^{
                [weakSelf.view layoutIfNeeded];
            }];
        }
        
       
    }];
}

// 积分不足
- (void)showWithTitle:(NSString *)title
{
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"提示" message:title preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction *okAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
     
    }];
    
 
    [okAction setValue:YLLOrgColor forKey:@"_titleTextColor"];
    
    
    [alertController addAction:okAction];
    
    [self presentViewController:alertController animated:YES completion:nil];
}



- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
